package com.szosen.util;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;

import com.szosen.database.AccessoryExamination;
import com.szosen.database.ChineseMedicineManage;
import com.szosen.database.DBService;
import com.szosen.database.DBService_backup;
import com.szosen.database.Examination;
import com.szosen.database.HealthAssessment;
import com.szosen.database.HealthRecord;
import com.szosen.database.InhospitalSituation;
import com.szosen.database.LifestySituation;
import com.szosen.database.MedicineSituation;
import com.szosen.database.NonimmuneInoculation;
import com.szosen.database.OldPeopleSelfCare;
import com.szosen.database.UploadRecord;
import com.szosen.database.Visit_info;
import com.szosen.database.Visit_info2;
import com.szosen.database.base_info;
import com.szosen.database.jwsjb;
import com.szosen.database.jwsss;
import com.szosen.database.jwssx;
import com.szosen.database.jwsws;
import com.szosen.database.niaoye;
import com.szosen.database.tiwen;
import com.szosen.database.xindian;
import com.szosen.database.xuetang;
import com.szosen.database.xueya;
import com.szosen.database.xueyang;
import com.szosen.json.database.ArchiveBean;
import com.szosen.json.database.JSONDBService;
import com.szosen.json.database.JSONDBService_json;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;

/***
 * 数据库操作工具 具有导出数据库文件.db到内存卡的功能
 *
 * @author geshenjibi
 *
 */
public class DatabaseTool {
    //数据备份的密码
    public static final String EXPORTDATA_PERMISSION_PASSWORD = "201707";
    public static final int WHAT_EXPORTDATA_MESSAGE_FAILED = 0x12;
    public static final int WHAT_EXPORTDATA_MESSAGE_SUCCESS = 0x13;
    public static final int WHAT_EXPORTDATA_MESSAGE_FINISH = 0x14;
    public static final int WHAT_EXPORTDATA_MESSAGE_MESSAGE = 0x16;
    public static final int WHAT_EXPORTDATA_MESSAGE_NO_SDCARD = 0x15;

    public static final int WHAT_IMPORTDATA_MESSAGE_FAILED = 0x22;
    public static final int WHAT_IMPORTDATA_MESSAGE_SUCCESS = 0x23;
    public static final int WHAT_IMPORTDATA_MESSAGE_NO_BACKUPFILE = 0x21;
    public static final int WHAT_IMPORTDATA_MESSAGE_FINISH = 0x24;
    public static final int WHAT_IMPORTDATA_MESSAGE_MESSAGE = 0x26;
    public static final int WHAT_IMPORTDATA_MESSAGE_NO_SDCARD = 0x25;
    private static final String EXPORTDATA_SUCCESS = "导出数据库文件成功";
    private static final String IMPORTDATA_SUCCESS = "导入数据库文件成功";
    //导出的数据库db文件的文件名
    public static final String EXPORTDATABASE_FILENAME = "export_health.db";
    //导出的数据库json操作的db文件的文件名
    public static final String EXPORTDATABASE_FILENAME_JSON = "export_health2.db";
    //导出数据库后保存的文件备份时间
    public static final String EXPORTDATABASE_TIME_FILENAME = "backupTime.bin";
    //内存存储安装app用于保存app数据的系统缓存根目录，
    public static final String baseCacheFile = "/data/data/com.szosen.jkzj";

    public static final String tfCardCacheFile = "/Android/data/com.szosen.jkzj";
    public static final String cacheFilePath = "/data/com.szosen.jkzj/shared_prefs";

    /***
     * 保存秘钥到sd卡中
     *
     * @param fileContent
     * @return
     */
    public static boolean saveBackupTime2TFCard(String fileContent, Context context) {
        File mainFile = null;
        // 获得sd卡根目录
        boolean result = false;
        //备份时间
        String backupPath = getTFCard_BackupPath(context);
        if (TextUtils.isEmpty(backupPath)) {
            return false;
        }
        File path = new File(backupPath);
        if (!path.exists()) {
            path.mkdirs();
        }
        mainFile = new File(backupPath, EXPORTDATABASE_TIME_FILENAME);
        try {
            if (!mainFile.exists()) {
                mainFile.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(mainFile);
            fos.write(fileContent.getBytes());
            fos.flush();
            fos.close();
            result = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /***
     * 读取秘钥
     *
     * @return
     */
    public static String getBackupTimeFromTFCard(Context context) {
        StringBuilder result = new StringBuilder();
        try {
            String backupPath = getTFCard_BackupPath(context);
            if (TextUtils.isEmpty(backupPath)) {
                return "";
            }
            File mainFile = new File(backupPath, EXPORTDATABASE_TIME_FILENAME);
            if (!mainFile.exists()) {
                return "";
            }
            BufferedReader br = new BufferedReader(new FileReader(mainFile));// 构造一个BufferedReader类来读取文件
            String s = null;
            while ((s = br.readLine()) != null) {// 使用readLine方法，一次读一行
                result.append(s);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return result.toString().trim();
    }

    /***
     * 导出database数据库文件到
     * @param handler
     */
    public static void exportDataBaseFile2SD(Context context, Handler handler) {
        new DatabaseTool().new ExportDatabaseTask(context, handler).execute();
    }

    /***
     * 从sd卡中导入数据
     * @param handler
     */
    public static void importDataFileFromSD(Context context, Handler handler) {
        new DatabaseTool().new ImportDatabaseTask(context, handler).execute();
    }

    /**
     * 如果TF卡中的村医版文件夹存在，则创建文件
     *
     * @param context
     * @return
     */
    public static boolean isTFCardDesExist(Context context) {
        //获取备份的文件夹目录
        String desPath = getTFCard_BackupPath(context);
        if (TextUtils.isEmpty(desPath)) {
            return false;
        }
        File des = new File(desPath);
        if (!des.exists()) {
            return false;
        } else {
            return true;
        }
        //获取备份的文件夹目录file对象
    }

    /***
     * 获取数据db文件的路径
     */
    public static String getDataBaseFilePath() {
        String path_database = Environment.getDataDirectory() + "/data/com.szosen.jkzj/databases/health.db";
        return path_database;
    }

    /***
     * 获取数据json操作的db文件的路径
     */
    public static String getDataBaseFilePath_json() {
        String path_database = Environment.getDataDirectory() + "/data/com.szosen.jkzj/databases/health2.db";
        return path_database;
    }

    /***
     * 获取TF卡中数据db文件的路径
     */
    public static String getTFDataBaseFilePath(Context context) {
        String path_database = getTFCard_BackupPath(context) + File.separator + EXPORTDATABASE_FILENAME;
        return path_database;
    }

    /***
     * 获取TF卡中数据db文件的路径
     */
    public static String getTFDataBaseFilePath_json(Context context) {
        String path_database = getTFCard_BackupPath(context) + File.separator + EXPORTDATABASE_FILENAME_JSON;
        return path_database;
    }

    /***
     * 获取TFCard的备份的文件夹目录
     */
    public static String getTFCard_BackupPath(Context context) {
        //TFcard的根目录路径
        String TF_path = StorageUtils.getTFCardPath(context);
        if (TextUtils.isEmpty(TF_path)) {
            return "";
        }
        String desPath = TF_path + tfCardCacheFile + File.separator + FileSaveUtil.getSDCardName();
        return desPath;
    }

    /***
     * 获取系统的sharedpreferences配置备份的文件夹目录
     */
    public static String getTFCard_Backup_SharedPreferenceDAtaPath() {
        return Environment.getDataDirectory() + cacheFilePath;
    }

    public class ExportDatabaseTask extends AsyncTask<Void, Void, String> {
        Handler mHandler;
        Context mContext;

        ExportDatabaseTask(Context context, Handler handler) {
            mHandler = handler;
            mContext = context;
        }

        //handler发送一条消息，导出完成还是失败。
        private void sendHandlerMessage(String msg) {
            if (mHandler != null) {
                mHandler.obtainMessage(WHAT_EXPORTDATA_MESSAGE_MESSAGE, msg).sendToTarget();
            }
        }

        @Override
        protected void onPreExecute() {

        }

        @Override
        protected String doInBackground(final Void... args) {
            // setting.db为apk里的一个数据库文件
            File dbFile = new File(getDataBaseFilePath());
            File dbFile_json = new File(getDataBaseFilePath_json());
            try {
                File src = new File(FileSaveUtil.getSDCardPath());
                //获取备份的文件夹目录
                String desPath = getTFCard_BackupPath(mContext);
                if (TextUtils.isEmpty(desPath)) {
                    mHandler.obtainMessage(WHAT_EXPORTDATA_MESSAGE_NO_SDCARD).sendToTarget();
                    return "";
                }
                //获取备份的文件夹目录file对象
                File des = new File(desPath);
                //需要备份的数据库目标db文件
                File desDatabaseFile = new File(des, EXPORTDATABASE_FILENAME);
                File desDatabaseFile_json = new File(des, EXPORTDATABASE_FILENAME_JSON);
                if (!des.exists()) {
                    des.mkdirs();
                }
                if (!desDatabaseFile.exists()) {
                    desDatabaseFile.createNewFile();
                } else {
                    desDatabaseFile.delete();
                }
                if (!desDatabaseFile_json.exists()) {
                    desDatabaseFile_json.createNewFile();
                } else {
                    desDatabaseFile_json.delete();
                }
                // 拷贝文件
                //拷贝数据库文件到备份文件夹的根目录下
                FileSaveUtil.copyDirectory(src.getPath(), des.getPath());
//                File desDatabaseFile2 = new File(FileSaveUtil.getSDCardPath(), EXPORTDATABASE_FILENAME);
                copyFile(dbFile, desDatabaseFile);
                copyFile(dbFile_json, desDatabaseFile_json);
//                copyFile(dbFile, desDatabaseFile2);
                //导出shared数据
                exportSharedPerferencesDataFile(mContext);
                DatabaseTool.saveBackupTime2TFCard(TimeHelper.getCurrentTime(), mContext);
            } catch (Exception e) {
                e.printStackTrace();
                mHandler.obtainMessage(WHAT_EXPORTDATA_MESSAGE_FAILED, e.getMessage()).sendToTarget();
                return "";
            }
            mHandler.obtainMessage(WHAT_EXPORTDATA_MESSAGE_SUCCESS, EXPORTDATA_SUCCESS).sendToTarget();
            return "";
        }

        @Override
        protected void onPostExecute(final String msg) {
            System.out.println("完成导出数据库文件至SD卡的任务");
        }

    }

    public class ImportDatabaseTask extends AsyncTask<Void, Void, String> {
        Handler mHandler;
        Context mContext;

        ImportDatabaseTask(Context context, Handler handler) {
            mHandler = handler;
            mContext = context;
        }

        //handler发送一条消息，导出完成还是失败。
        private void sendHandlerMessage(String msg) {
            if (mHandler != null) {
                mHandler.obtainMessage(WHAT_EXPORTDATA_MESSAGE_MESSAGE, msg).sendToTarget();
            }
        }

        @Override
        protected void onPreExecute() {

        }

        //导出了health.db health2.db 到export
        @Override
        protected String doInBackground(final Void... args) {
            // setting.db为apk里的一个数据库文件
            String tf_dataBaseFilePath = getTFDataBaseFilePath(mContext);
            String tf_dataBaseFilePath_JSON = getTFDataBaseFilePath_json(mContext);
            try {
                File des = new File(FileSaveUtil.getSDCardPath());
                //获取备份的文件夹目录
                String srcPath = getTFCard_BackupPath(mContext);
                if (TextUtils.isEmpty(srcPath)) {
                    mHandler.obtainMessage(WHAT_IMPORTDATA_MESSAGE_NO_SDCARD).sendToTarget();
                    return "";
                }
                //获取备份的文件夹目录file对象
                File src = new File(srcPath);
                if (!src.exists()) {
//                    mHandler.obtainMessage(WHAT_IMPORTDATA_MESSAGE_NO_BACKUPFILE).sendToTarget();
                    return "";
                }
                FileSaveUtil.copyDirectory(src.getPath(), des.getPath());
                //文件不存在，找不到备份的文件夹
                //由于6.0只能在在TF卡中以该应用命名的文件夹创建文件.且在设置中删除应用数据或者卸载软件时，该文件夹会删除。
                //所以创建文件夹时。
//                File desDatabaseFile2 = new File(FileSaveUtil.getSDCardPath() + EXPORTDATABASE_FILENAME);
//                if (desDatabaseFile2.exists()) {
//                    boolean ok = importDatabaseFileFromTF(desDatabaseFile2.getPath(), mContext);
//                    System.out.println("数据库从内部存储回复成功=" + ok);
//                    if (ok) {
//                        insertDataBaseFromBackupDB(mContext);
//                    }
//                }
                // 拷贝数据库文件所有内容
                boolean ok = importDatabaseFileFromTF(tf_dataBaseFilePath, mContext);
//                System.out.println("数据库从TF卡恢复成功=" + ok);
                if (ok) {
                    insertDataBaseFromBackupDB(mContext);
                }

                // 拷贝数据库文件所有内容
                boolean ok2 = importDatabaseFileFromTF_JSON(tf_dataBaseFilePath_JSON, mContext);
//                System.out.println("数据库从TF卡恢复成功=" + ok);
                if (ok2) {
                    insertDataBaseFromBackupDB_JSON(mContext);
                }
                //导入shared数据
                importSharedPerferencesDataFile(mContext);
            } catch (Exception e) {
                e.printStackTrace();
                mHandler.obtainMessage(WHAT_IMPORTDATA_MESSAGE_FAILED, e.getMessage()).sendToTarget();
                return "";
            }
            mHandler.obtainMessage(WHAT_IMPORTDATA_MESSAGE_SUCCESS, EXPORTDATA_SUCCESS).sendToTarget();
            return "";
        }

        @Override
        protected void onPostExecute(final String msg) {
            System.out.println("完成导入数据的任务");
        }
    }


    private static void insertDataBaseFromBackupDB_JSON(Context context) {
        JSONDBService_json.getInstance(context);
        List<Object> ArchiveBeans = JSONDBService_json.getAll(new ArchiveBean());
        if (ArchiveBeans != null) {
            for (int i = 0; i < ArchiveBeans.size(); i++) {
                ArchiveBean ab = (ArchiveBean) ArchiveBeans.get(i);
                boolean bb = JSONDBService.add(ab);
                System.out.println("jsonDBService=" + bb);
            }
        }
    }

    private static void insertDataBaseFromBackupDB(Context context) {
        //从备份的数据库文件获取数据，一条条的插入到现有的数据库中。
        DBService_backup.getInstance(context);
        List<Object> hrs = DBService_backup.getAll(new HealthRecord());
        if (hrs != null) {
            for (int i = 0; i < hrs.size(); i++) {
                HealthRecord hr = (HealthRecord) hrs.get(i);
                DBService.add(hr);
            }
        }
        List<Object> jwsjbs = DBService_backup.getAll(new jwsjb());
        if (jwsjbs != null) {
            for (int i = 0; i < jwsjbs.size(); i++) {
                jwsjb j = (jwsjb) jwsjbs.get(i);
                DBService.add(j);
            }
        }
        List<Object> jwssss = DBService_backup.getAll(new jwsss());
        if (jwssss != null) {
            for (int i = 0; i < jwssss.size(); i++) {
                jwsss j = (jwsss) jwssss.get(i);
                DBService.add(j);
            }
        }
        List<Object> jwssxs = DBService_backup.getAll(new jwssx());
        if (jwssxs != null) {
            for (int i = 0; i < jwssxs.size(); i++) {
                jwssx j = (jwssx) jwssxs.get(i);
                DBService.add(j);
            }
        }
        List<Object> jwswss = DBService_backup.getAll(new jwsws());
        if (jwswss != null) {
            for (int i = 0; i < jwswss.size(); i++) {
                jwsws j = (jwsws) jwswss.get(i);
                DBService.add(j);
            }
        }
        List<Object> base_infos = DBService_backup.getAll(new base_info());
        if (base_infos != null) {
            for (int i = 0; i < base_infos.size(); i++) {
                base_info b = (base_info) base_infos.get(i);
                DBService.add(b);
            }
        }
        List<Object> Examinations = DBService_backup.getAll(new Examination());
        if (Examinations != null) {
            for (int i = 0; i < Examinations.size(); i++) {
                Examination e = (Examination) Examinations.get(i);
                DBService.add(e);
            }
        }
        List<Object> AccessoryExaminations = DBService_backup.getAll(new AccessoryExamination());
        if (AccessoryExaminations != null) {
            for (int i = 0; i < AccessoryExaminations.size(); i++) {
                AccessoryExamination a = (AccessoryExamination) AccessoryExaminations.get(i);
                DBService.add(a);
            }
        }
        List<Object> InhospitalSituations = DBService_backup.getAll(new InhospitalSituation());
        if (InhospitalSituations != null) {
            for (int i = 0; i < InhospitalSituations.size(); i++) {
                InhospitalSituation ihs = (InhospitalSituation) InhospitalSituations.get(i);
                DBService.add(ihs);
            }
        }
        List<Object> MedicineSituations = DBService_backup.getAll(new MedicineSituation());
        if (MedicineSituations != null) {
            for (int i = 0; i < MedicineSituations.size(); i++) {
                MedicineSituation ms = (MedicineSituation) MedicineSituations.get(i);
                DBService.add(ms);
            }
        }
        List<Object> NonimmuneInoculations = DBService_backup.getAll(new NonimmuneInoculation());
        if (NonimmuneInoculations != null) {
            for (int i = 0; i < NonimmuneInoculations.size(); i++) {
                NonimmuneInoculation ni = (NonimmuneInoculation) NonimmuneInoculations.get(i);
                DBService.add(ni);
            }
        }
        List<Object> HealthAssessments = DBService_backup.getAll(new HealthAssessment());
        if (HealthAssessments != null) {
            for (int i = 0; i < HealthAssessments.size(); i++) {
                HealthAssessment ha = (HealthAssessment) HealthAssessments.get(i);
                DBService.add(ha);
            }
        }
        List<Object> Visit_infos = DBService_backup.getAll(new Visit_info());
        if (Visit_infos != null) {
            for (int i = 0; i < Visit_infos.size(); i++) {
                Visit_info vi = (Visit_info) Visit_infos.get(i);
                DBService.add(vi);
            }
        }
        List<Object> Visit_info2s = DBService_backup.getAll(new Visit_info2());
        if (Visit_info2s != null) {
            for (int i = 0; i < Visit_info2s.size(); i++) {
                Visit_info2 vi = (Visit_info2) Visit_info2s.get(i);
                DBService.add(vi);
            }
        }
        List<Object> ChineseMedicineManages = DBService_backup.getAll(new ChineseMedicineManage());
        if (ChineseMedicineManages != null) {
            for (int i = 0; i < ChineseMedicineManages.size(); i++) {
                ChineseMedicineManage cmm = (ChineseMedicineManage) ChineseMedicineManages.get(i);
                DBService.add(cmm);
            }
        }
        List<Object> OldPeopleSelfCares = DBService_backup.getAll(new OldPeopleSelfCare());
        if (OldPeopleSelfCares != null) {
            for (int i = 0; i < OldPeopleSelfCares.size(); i++) {
                OldPeopleSelfCare os = (OldPeopleSelfCare) OldPeopleSelfCares.get(i);
                DBService.add(os);
            }
        }
        List<Object> LifestySituations = DBService_backup.getAll(new LifestySituation());
        if (LifestySituations != null) {
            for (int i = 0; i < LifestySituations.size(); i++) {
                LifestySituation ls = (LifestySituation) LifestySituations.get(i);
                DBService.add(ls);
            }
        }
        List<Object> xueyas = DBService_backup.getAll(new xueya());
        if (xueyas != null) {
            for (int i = 0; i < xueyas.size(); i++) {
                xueya xy = (xueya) xueyas.get(i);
                DBService.add(xy);
            }
        }
        List<Object> xueyangs = DBService_backup.getAll(new xueyang());
        if (xueyangs != null) {
            for (int i = 0; i < xueyangs.size(); i++) {
                xueyang xy = (xueyang) xueyangs.get(i);
                DBService.add(xy);
            }
        }
        List<Object> tiwens = DBService_backup.getAll(new tiwen());
        if (tiwens != null) {
            for (int i = 0; i < tiwens.size(); i++) {
                tiwen tw = (tiwen) tiwens.get(i);
                DBService.add(tw);
            }
        }
        List<Object> xuetangs = DBService_backup.getAll(new xuetang());
        if (xuetangs != null) {
            for (int i = 0; i < xuetangs.size(); i++) {
                xuetang xt = (xuetang) xuetangs.get(i);
                DBService.add(xt);
            }
        }
        List<Object> niaoyes = DBService_backup.getAll(new niaoye());
        if (niaoyes != null) {
            for (int i = 0; i < niaoyes.size(); i++) {
                niaoye ny = (niaoye) niaoyes.get(i);
                DBService.add(ny);
            }
        }
        List<Object> xindians = DBService_backup.getAll(new xindian());
        if (xindians != null) {
            for (int i = 0; i < xindians.size(); i++) {
                xindian xd = (xindian) xindians.get(i);
                DBService.add(xd);
            }
        }
        List<Object> UploadRecords = DBService_backup.getAll(new UploadRecord());
        if (UploadRecords != null) {
            for (int i = 0; i < UploadRecords.size(); i++) {
                UploadRecord ur = (UploadRecord) UploadRecords.get(i);
                DBService.add(ur);
            }
        }
    }


    /**
     * 导出shared存储文件
     */
    public static void exportSharedPerferencesDataFile(Context context) {
        //获取内部存储路径
        String filePath = DatabaseTool.getTFCard_Backup_SharedPreferenceDAtaPath();
        String fileTFPath = getTFCard_BackupPath(context);
        try {
            File file_userdata_cache = new File(filePath + "/userdata.xml");
            File file_userdata_sdcard = new File(fileTFPath + "/userdata.xml");
            File file_padhealth_cache = new File(filePath + "/padhealth.xml");
            File file_padhealth_sdcard = new File(fileTFPath + "/padhealth.xml");
            //平板设置的文件
            DatabaseTool.copyFile(file_userdata_cache, file_userdata_sdcard);
//            //设备连接的配置文件
            DatabaseTool.copyFile(file_padhealth_cache, file_padhealth_sdcard);
//            恢复数据
//            DatabaseTool.copyFile(file_userdata_sdcard, file_userdata_cache);
//            //设备连接的配置文件
//            DatabaseTool.copyFile(file_padhealth_sdcard, file_padhealth_cache);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 恢复shared存储文件
     */
    public static void importSharedPerferencesDataFile(Context context) {
        //获取内部存储路径
        String filePath = DatabaseTool.getTFCard_Backup_SharedPreferenceDAtaPath();
        String fileTFPath = getTFCard_BackupPath(context);
        try {
            File file_userdata_cache = new File(filePath + "/userdata.xml");
            File file_userdata_sdcard = new File(fileTFPath + "/userdata.xml");
            File file_padhealth_cache = new File(filePath + "/padhealth.xml");
            File file_padhealth_sdcard = new File(fileTFPath + "/padhealth.xml");
            //平板设置的文件
//            DatabaseTool.copyFile(file_userdata_cache, file_userdata_sdcard);
//            //设备连接的配置文件
//            DatabaseTool.copyFile(file_padhealth_cache, file_padhealth_sdcard);
//            恢复数据
            boolean b1 =  DatabaseTool.copyFile(file_userdata_sdcard, file_userdata_cache);
            System.out.println(b1);
//            //设备连接的配置文件
            boolean b = DatabaseTool.copyFile(file_padhealth_sdcard, file_padhealth_cache);
            System.out.println(b);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //将读取到的数据库插入app的数据库中
    public static boolean importDatabaseFileFromTF(String dataBaseFilepath, Context context) {
        //需要复制到data目录下的数据库文件名
        String desPath = getTFCard_BackupPath(context);
        if (TextUtils.isEmpty(desPath)) {
            return false;
        }

        String despath_databasebackin = Environment.getDataDirectory() + "/data/com.szosen.jkzj/databases/" + EXPORTDATABASE_FILENAME;
        File srcDatabaseFile = new File(dataBaseFilepath);
        File desDatabaseFile = new File(despath_databasebackin);
        //需要备份的数据库目标db文件
        try {
            //如果文件不存在，则返回失败。
            if (!srcDatabaseFile.exists()) {
                return false;
            }
            if (desDatabaseFile.exists()) {
                desDatabaseFile.delete();
            }
            System.out.println("读取外部db文件src=" + srcDatabaseFile.getPath() + ",des=" + despath_databasebackin);
            copyFile(srcDatabaseFile, desDatabaseFile);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    //将读取到的数据库插入app的数据库中
    public static boolean importDatabaseFileFromTF_JSON(String dataBaseFilepath, Context context) {
        //需要复制到data目录下的数据库文件名
        String desPath = getTFCard_BackupPath(context);
        if (TextUtils.isEmpty(desPath)) {
            return false;
        }

        String despath_databasebackin = Environment.getDataDirectory() + "/data/com.szosen.jkzj/databases/" + EXPORTDATABASE_FILENAME_JSON;
        File srcDatabaseFile = new File(dataBaseFilepath);
        File desDatabaseFile = new File(despath_databasebackin);
        //需要备份的数据库目标db文件
        try {
            //如果文件不存在，则返回失败。
            if (!srcDatabaseFile.exists()) {
                return false;
            }
            if (desDatabaseFile.exists()) {
                desDatabaseFile.delete();
            }
            System.out.println("读取外部db文件src=" + srcDatabaseFile.getPath() + ",des=" + despath_databasebackin);
            copyFile(srcDatabaseFile, desDatabaseFile);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    public static boolean copyFile(File src, File dst) throws IOException {
        FileChannel inChannel = new FileInputStream(src).getChannel();
        if (!dst.exists()) {
            dst.createNewFile();
        } else {
            dst.delete();
        }
        FileChannel outChannel = new FileOutputStream(dst).getChannel();
        try {
            inChannel.transferTo(0, inChannel.size(), outChannel);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (inChannel != null)
                inChannel.close();
            if (outChannel != null)
                outChannel.close();
        }

    }


    /**
     * 获取外置SD卡路径以及TF卡的路径
     * <p>
     * 返回的数据：paths.get(0)肯定是外置SD卡的位置，因为它是primary external storage.
     *
     * @return 所有可用于存储的不同的卡的位置，用一个List来保存
     */
    public static List<String> getExtSDCardPathList() {
        List<String> paths = new ArrayList<String>();
        String extFileStatus = Environment.getExternalStorageState();
        File extFile = Environment.getExternalStorageDirectory();
        //首先判断一下外置SD卡的状态，处于挂载状态才能获取的到
        if (extFileStatus.equals(Environment.MEDIA_MOUNTED)
                && extFile.exists() && extFile.isDirectory()
                && extFile.canWrite()) {
            //外置SD卡的路径
            paths.add(extFile.getAbsolutePath());
        }
        try {
            // obtain executed result of command line code of 'mount', to judge
            // whether tfCard exists by the result
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec("mount");
            InputStream is = process.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            int mountPathIndex = 1;
            while ((line = br.readLine()) != null) {
                // format of sdcard file system: vfat/fuse
                if ((!line.contains("fat") && !line.contains("fuse") && !line
                        .contains("storage"))
                        || line.contains("secure")
                        || line.contains("asec")
                        || line.contains("firmware")
                        || line.contains("shell")
                        || line.contains("obb")
                        || line.contains("legacy") || line.contains("data")) {
                    continue;
                }
                String[] parts = line.split(" ");
                int length = parts.length;
                if (mountPathIndex >= length) {
                    continue;
                }
                String mountPath = parts[mountPathIndex];
                if (!mountPath.contains("/") || mountPath.contains("data")
                        || mountPath.contains("Data")) {
                    continue;
                }
                File mountRoot = new File(mountPath);
                if (!mountRoot.exists() || !mountRoot.isDirectory()
                        || !mountRoot.canWrite()) {
                    continue;
                }
                boolean equalsToPrimarySD = mountPath.equals(extFile
                        .getAbsolutePath());
                if (equalsToPrimarySD) {
                    continue;
                }
                //扩展存储卡即TF卡或者SD卡路径
                paths.add(mountPath);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return paths;
    }

}
